#pragma once
#include <memory>
#include <vector>
#include <poll.h>
#include <algorithm>
#include "../logsystem/logger/log.h"
#include "Socket.hpp"
using namespace Net_Work;
const int gbacklog = 5;
const int gnum = 1024;
class PollServer
{
public:
    PollServer(int port) : _port(port), _listensock(new TcpSocket()), _stop(false), _num(gnum)
    {
    }

    void Init()
    {
        // 创建
        _listensock->BuildListenSocketMethod(_port, gbacklog);
        // 初始化
        _fds = new struct pollfd[_num];
        for (int i = 0; i < _num; i++)
        {
            _fds[i].revents = 0;
            _fds[i].events = 0;
            _fds[i].fd = -1;
        }
        // 添加进监听套接字
        _fds[0].fd = _listensock->GetSockfd();
        _fds[0].events |= POLLIN;
    }

    void Loop()
    {
        _stop = false;
        while (!_stop)
        {
            //-1表示阻塞 0非阻塞  1000 1s阻塞
            int timeout = 2000; // 2秒
            // int n = select(_listensock->GetSockfd() + 1, &rfds, nullptr, nullptr, &tv);
            PrintSet();
            int n = poll(_fds, _num, timeout);
            switch (n)
            {
            case 0:
                ILOG("事件未就绪...");
                break;
            case -1:
                DLOG("select error");
            default:
                ILOG("事件就绪,last time");
                HandlerEvent();
                break;
            }
        }
        _stop = true;
    }

    ~PollServer()
    {
        _stop = true;
        _listensock->CloseSockFd();
        delete[] _fds;
    }

private:
    void HandlerEvent()
    {
        // 遍历rfds
        for (int i = 0; i < _num; i++)
        {
            int fd = _fds[i].fd;
            if (fd != -1)
            {
                int short revent = _fds[i].revents;
                if (revent & POLLIN)
                {
                    // 一个连接就绪的可能:1.listen  2.read
                    if (fd == _listensock->GetSockfd())
                    {
                        HandlerAccept();
                    }
                    // 普通sock //简单的读写
                    else
                    {
                        HandlerRead(i);
                    }
                }
            }
        }
    }
    void HandlerAccept()
    {
        ILOG("获取一个新连接!");
        std::string clientip;
        uint16_t clientport;
        Socket *sock = _listensock->AcceptConnection(&clientip, &clientport);
        if (!sock)
        {
            DLOG("获取连接失败!");
            return;
        }

        ILOG("获取连接成功!ip:%s port:%d", clientip.c_str(), clientport);
        // 添加到fd_nums
        int i = 0;
        for (; i < _num; i++)
        {
            if (_fds[i].fd == -1)
            {
                _fds[i].fd = sock->GetSockfd();
                _fds[i].events |= POLLIN;
                break;
            }
        }
        // 满了!!
        if (i == _num)
        {
            WLOG("accept error!link full!!");
            sock->CloseSockFd();
            delete sock;
        }
    }

    void HandlerRead(int i)
    {
        char buffer[1024];
        ssize_t ret = recv(_fds[i].fd, buffer, sizeof(buffer) - 1, 0);
        if (ret > 0)
        {
            buffer[ret] = 0;
            std::cout << "client say#" << buffer << std::endl;
            // 发回消息
            std::string tmp = "你好client,我是server:";
            tmp += buffer;
            send(_fds[i].fd, tmp.c_str(), tmp.size(), 0);
        }
        // 异常或者直接关闭
        else
        {
            ILOG("link break!!! maybe client quit or error");
            // 关闭描述符
            // 将数组的值置为空
            close(_fds[i].fd);
            _fds[i].events = 0;
            _fds[i].fd = -1;
        }
    }
    void PrintSet()
    {
        std::cout << "fd_nums:";
        for (int i = 0; i < _num; i++)
        {
            if (_fds[i].fd != -1)
            {
                std::cout << _fds[i].fd << " ";
            }
        }
        std::cout << std::endl;
    }

private:
    int _port;
    bool _stop;
    // std::vector<Socket *> fd_nums; // 事件先添加进描述符数组
    struct pollfd *_fds;
    int _num;
    std::unique_ptr<Socket> _listensock;
};